﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using EMailClient;



namespace RISMOTAXDP.EmailService
{


    public class DataBaseInfo
    {
        /*
        /// <summary>
        /// 系统参数信息表查询语句
        /// </summary>
        private const string SQL_SELECT_SYSTEMPARA = "SELECT MailSendType,MailAttacheSavePath,ReportSavePath,TemplatePath,MailContentPath,ItemNameA,ItemNameB,DecimalDigits FROM SP_SystemPara";
       */

        /// <summary>
        /// 邮件服务器参数表查询语句
        /// </summary>
        private const string SQL_SELECT_MAILSERVER = @"select 
d1.Operation_ID,
d1.OperationCode,
d1.OperationMailTemplateName,
d1.OperationName,
d3.SMTPAddress,
d3.Port,
d3.[User],
d3.PWD,
d3.MailFrom
from TBL_MailOperation as d1
left join TBL_MailSMTPRoute as d2
on d1.Operation_ID  = d2.Operation_ID
left join TBL_SMTPGeteway as d3
on d2.SMTP_ID = d3.SMTP_ID";

        private const string SQL_SELECT_MAILOP = @"select 
Operation_ID, 
OperationCode, 
OperationName, 
OperationMailTemplateName 
from TBL_MailOperation";

        #region 属性
        /// <summary>
        /// 邮件服务器列表
        /// </summary>
        private MailServerInfoList m_MailServerList;
        /// <summary>
        /// SMTP邮件服务器列表
        /// </summary>
        private List<MailServerInfo> m_SMTPServerList;

        /// <summary>
        /// 邮件业务代码列表
        /// </summary>
        private MailOperationInfoList m_MailOperationList;

        /// <summary>
        /// 邮件发送方式
        /// </summary>
        private string m_MailSendType;
        /// <summary>
        /// 邮件附件保存位置
        /// </summary>
        private string m_MailAttacheSavePath;


        /// <summary>
        /// 初始化状态
        /// </summary>
        private bool m_Initialized;
        /// <summary>
        /// 获取邮件服务器路由列表
        /// </summary>
        public MailServerInfoList MailServerList
        {
            get { return m_MailServerList; }
        }
        /// <summary>
        /// 获取SMTP邮件服务器列表
        /// </summary>
        public List<MailServerInfo> SMTPServerList
        {
            get { return m_SMTPServerList; }
        }

        public MailOperationInfoList MailOperationList
        {
            get { return m_MailOperationList; }
        }

        /// <summary>
        /// 获取邮件发送方式
        /// </summary>
        public string MailSendType
        {
            get { return m_MailSendType; }
        }
        /// <summary>
        /// 获取邮件附件保存位置
        /// </summary>
        public string MailAttacheSavePath
        {
            get { return m_MailAttacheSavePath; }
        }

        /// <summary>
        /// 返回数据库信息初始化状态
        /// </summary>
        public bool Initialized
        {
            get { return m_Initialized; }
        }
        #endregion

        /// <summary>
        /// 类初始化
        /// </summary>
        public DataBaseInfo()
        {
            m_MailServerList = new MailServerInfoList();
            m_MailOperationList = new MailOperationInfoList();
            m_Initialized = false;
        }

        /// <summary>
        /// 初始化数据库信息
        /// </summary>
        /// <param name="conn">数据库连接</param>
        /// <returns>返回执行是否成功</returns>
        public bool Initialize()
        {
            SqlConnection conn = GlobalObject.CreateConnect();
            if (conn == null)
            {
                GlobalObject.WriteOperationLog("E80000002", null);
                return false;
            }
            try
            {
                GlobalObject.WriteSystemLog("S00000006", null);

                //获取SMTP邮件服务器列表
                m_MailServerList.Clear();
                using (SqlDataReader reader = SQLHelper.ExecuteReader(conn, CommandType.Text, SQL_SELECT_MAILSERVER))
                {
                    while (reader.Read())
                    {
                        string OpCode = reader[1].ToString();
                        if (!m_MailServerList.ContainsKey(OpCode))
                        {
                            m_MailServerList.Add(OpCode, new MailServerInfo(
                                reader.IsDBNull(4) ? "" : reader.GetString(4), //SMTPAddress
                                reader.IsDBNull(5) ? 25 : Convert.ToInt32(reader.GetString(5)),  //SMTPPort
                                reader.IsDBNull(6) ? "" : reader.GetString(6), //user
                                reader.IsDBNull(7) ? "" : reader.GetString(7)  //pwd

                                ));
                        }
                    }
                }

                foreach ( string key in m_MailServerList.Keys)
                {
                    if (!m_MailServerList[key].IsAvailable()) throw new Exception("MAIL SERVER SETTING ERROR.");
                }

                //获取邮件业务代码列表

                m_MailOperationList.Clear();
                using (SqlDataReader reader_MailOP= SQLHelper.ExecuteReader(conn, CommandType.Text, SQL_SELECT_MAILOP))
                {
                    while (reader_MailOP.Read())
                    {
                        string MailOPCode = reader_MailOP[1].ToString();
                        if (!m_MailOperationList.ContainsKey(MailOPCode))
                        {
                            m_MailOperationList.Add(MailOPCode, new MailOperationInfo(
                                MailOPCode,
                                reader_MailOP.IsDBNull(2) ? "" : reader_MailOP.GetString(2),
                                reader_MailOP.IsDBNull(3) ? "" : reader_MailOP.GetString(3)

                                ));
                        }
                    }
                }

                GlobalObject.WriteSystemLog("S00000007", null);
            }
            catch (Exception ex)
            {
                GlobalObject.WriteOperationLog("E80000003", ex);
                return false;
            }
 
            m_SMTPServerList = m_MailServerList.GetSMTPServers();
            m_Initialized = true;
            GlobalObject.CloseConnect(conn);
            return m_Initialized;
        }

        /// <summary>
        /// 重新初始化系统信息
        /// </summary>
        public void ReInitialize()
        {
            m_Initialized = false;
        }
    }

    public class MailServerInfo
    {
        /// <summary>
        /// 邮件SMTP服务器IP地址
        /// </summary>
        private string m_MailSMTPServerAddr;
        
        /// <summary>
        /// 邮件SMTP服务器端口
        /// </summary>
        private int m_MailSMTPServerPort;
       
        /// <summary>
        /// 邮件服务器登录用户名
        /// </summary>
        private string m_MailServerUser;
        
        /// <summary>
        /// 邮件服务器登录密码
        /// </summary>
        private string m_MailServerPwd;

        /// <summary>
        /// 获取邮件SMTP服务器IP地址
        /// </summary>
        public string MailSMTPServerAddr
        {
            get
            {

                    return m_MailSMTPServerAddr.Trim();

            }
        }
        /// <summary>
        /// 获取邮件SMTP服务器端口
        /// </summary>
        public int MailSMTPServerPort
        {
            get
            {
                return m_MailSMTPServerPort;
            }
        }
        
        /// <summary>
        /// 获取邮件服务器登录用户名
        /// </summary>
        public string MailServerUser
        {
            get
            {

                return m_MailServerUser;


            }
        }
        
        /// <summary>
        /// 获取邮件服务器登录用户名
        /// </summary>
        public string MailServerPwd
        {
            get { return m_MailServerPwd; }
        }


        /// <summary>
        /// 获取邮箱地址标识
        /// </summary>
        public string MailAddress
        {
            get
            {

                //return m_MailServerUser.Trim() + m_MailPOP3ServerAddr.Trim();
                return m_MailServerUser.Trim();

            }
        }
        
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="mailSMTPServerAddr">邮件SMTP服务器IP地址</param>
        /// <param name="mailSMTPServerPort">邮件SMTP服务器端口地址</param>
        /// <param name="mailServerUser">邮件服务器登录用户名</param>
        /// <param name="mailServerPwd">邮件服务器登录密码</param>
        public MailServerInfo(string mailSMTPServerAddr,int mailSMTPServerPort,
            string mailServerUser, string mailServerPwd)
        {
            m_MailSMTPServerAddr = mailSMTPServerAddr;
            m_MailServerUser = mailServerUser;
            m_MailServerPwd = mailServerPwd;

            try
            {
                m_MailSMTPServerPort = mailSMTPServerPort;
            }
            catch
            {
                //默认为25
                m_MailSMTPServerPort = 25;
            }

 

        }

        /// <summary>
        /// 判断配置是否可用
        /// </summary>
        /// <returns>返回状态</returns>
        public bool IsAvailable()
        {
            //SMTP服务器配置
            if (m_MailSMTPServerAddr == null || m_MailSMTPServerAddr == string.Empty) return false;

            //if (m_MailPOP3ServerAddr == null || m_MailPOP3ServerAddr == string.Empty) return false;


            return true;
        }



        /// <summary>
        /// 判断SMTP信息是否相同
        /// </summary>
        /// <param name="server">邮件服务器信息</param>
        /// <returns>返回是否相同</returns>
        public bool EqualSMTP(MailServerInfo server)
        {

                return this.MailSMTPServerAddr == server.MailSMTPServerAddr
                    && this.MailServerUser == server.MailServerUser
                    && this.MailServerPwd == server.MailServerPwd;

        }
 

  

    }

    public class MailServerInfoList : Dictionary<string, MailServerInfo>
    {
        /// <summary>
        /// 根据业务类型ID获取邮件服务器信息
        /// </summary>
        /// <param name="key">业务类型ID</param>
        /// <returns>返回邮件服务器信息</returns>
        public new MailServerInfo this[string key]
        {
            get
            {
                if (string.IsNullOrEmpty(key))
                {
                    return null;
                }

                if (base.ContainsKey(key))
                {
                    return base[key];
                }
               // else if (base.ContainsKey(0))
               // {
               //     return base[0];
               // }
                else
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 获取SMTP邮件服务器列表
        /// </summary>
        /// <returns>返回不重覆的SMTP邮件服务器列表</returns>
        public List<MailServerInfo> GetSMTPServers()
        {
            List<MailServerInfo> lst = new List<MailServerInfo>();
            foreach (string key in base.Keys)
            {
                MailServerInfo orgin = base[key];
                for (int i = 0; i < lst.Count; i++)
                {
                    if (lst[i].EqualSMTP(orgin))
                    {
                        orgin = null;
                        break;
                    }
                }
                if (orgin != null)
                {
                    lst.Add(orgin);
                }
            }
            return lst;
        }



    }

    public class MailOperationInfo
    {
        /// <summary>
        /// 业务代码
        /// </summary>
        public string OpCode { get; set; }
        /// <summary>
        /// 业务名称
        /// </summary>
        public string OpName { get; set; }
        /// <summary>
        /// 邮件模板
        /// </summary>
        public string MailTemplate { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="opCode"></param>
        /// <param name="opName"></param>
        /// <param name="mailTemplate"></param>
        public MailOperationInfo(string opCode, string opName, string mailTemplate)
        {
            OpCode = opCode;
            OpName = opName;
            MailTemplate = mailTemplate;
        }

    }

    public class MailOperationInfoList : Dictionary<string, MailOperationInfo>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key">业务类型ID</param>
        /// <returns></returns>
        public new MailOperationInfo this[string key]
        {
            get
            {
                if (string.IsNullOrEmpty(key))
                {
                    return null;
                }
                if (base.ContainsKey(key))
                {
                    return base[key];
                }
                else
                {
                    return null;
                }
            }

        }

    }


}
